import { memo, useEffect, useState } from 'react';
import { Image as KonvaImage } from 'react-konva';
import { CanvasSize } from './ImagePreview';

const LayerImageItem = (props: { src: string; containerSize: CanvasSize }) => {
  const { src, containerSize } = props;
  const [loadedImageElement, setLoadedImageElement] =
    useState<HTMLImageElement | null>(null);

  useEffect(() => {
    if (!src) {
      return;
    }

    const tempImage = new Image();

    tempImage.onload = () => {
      setLoadedImageElement(tempImage);
    };

    tempImage.src = src;
  }, [src]);

  if (!src) {
    return null;
  }

  return loadedImageElement ? (
    <KonvaImage x={0} y={0} image={loadedImageElement} listening={false} />
  ) : null;
};

export default memo(LayerImageItem);
